package demo.generator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import net.oschina.renyong.query.generator.QuerySqlGenerator;
import net.oschina.renyong.query.generator.plugin.DefaultCountSqlOptimizer;
import net.oschina.renyong.query.generator.plugin.ICountSqlOptimizer;

public class DemoMysqlQueryGenerator {

	/**
	 * 从properties中获取项目配置信息
	 */
	private static final ResourceBundle rb = ResourceBundle.getBundle("mp_generator");

	// 目标项目根路径
	private static final String PROJECT_DIR = rb.getString("mpg.project_dir");
	// 目标项目的基础包名
	private static final String PROJECT_PACKAGE = rb.getString("mpg.project_package");

	// 数据库相关配置
	// 数据库类型
	private static final DbType DB_TYPE = DbType.MYSQL;
	// 数据库连接驱动类
	private static final String DB_DRIVER_NAME = rb.getString("mpg.db_driver_name");
	// 数据库连接用户名
	private static final String DB_USERNAME = rb.getString("mpg.db_username");
	// 数据库连接密码
	private static final String DB_PASSWORD = rb.getString("mpg.db_password");
	// 数据库连接URL
	private static final String DB_URL = rb.getString("mpg.db_url");

	public static void main(String[] args) {
		// 初始化查询总数SQL优化器
		ICountSqlOptimizer countSqlOptimizer = new DefaultCountSqlOptimizer();

		// 全局配置
		GlobalConfig globalConfig = new GlobalConfig();
		globalConfig.setOutputDir(PROJECT_DIR);
		globalConfig.setAuthor("idea");

		// 数据库配置
		DataSourceConfig dataSourceConfig = new DataSourceConfig();
		dataSourceConfig.setDbType(DB_TYPE);
		dataSourceConfig.setDriverName(DB_DRIVER_NAME);
		dataSourceConfig.setUsername(DB_USERNAME);
		dataSourceConfig.setPassword(DB_PASSWORD);
		dataSourceConfig.setUrl(DB_URL);

		// 包 配置
		PackageConfig packageConfig = new PackageConfig();
		packageConfig.setParent(PROJECT_PACKAGE);

		QuerySqlGenerator generator = new QuerySqlGenerator();
		generator.setGlobalConfig(globalConfig);
		generator.setDataSourceConfig(dataSourceConfig);
		generator.setPackageConfig(packageConfig);
		// 表名生成策略
		generator.setNamingStrategy(NamingStrategy.underline_to_camel);
		// 设置查询总数SQL优化器
		generator.setCountSqlOptimizer(countSqlOptimizer);
		// 设置特殊查询配置文件的位置
		generator.setResourceLocation("classpath:query_sql.xml");

		// 执行代码生成
		generator.executeGenerate();
	}

	/**
	 * 判断表名是否符合预设的匹配规则<br>
	 * 表名匹配一个规则即可
	 * @param tableName 表名
	 * @param tblMatchList 表名匹配规则（正则表达式）
	 * @return 表名的规则匹配结果
	 */
	private static boolean isTblMatch(String tableName, List<String> tblMatchList) {
		for (String tbMatch : tblMatchList) {
			if (tableName.matches(tbMatch)) {
				return true;
			}
		}
		return false;
	}

	private static String[] getDbTblOrView(DataSourceConfig config, String tblOrViewStr, boolean isTbl) {
		if (StringUtils.isEmpty(StringUtils.trimWhitespace(tblOrViewStr))) {
			return null;
		}
		String[] temp = tblOrViewStr.split(",");
		// 获取用于表匹配的数据集合
		List<String> tbMatchList = Arrays.stream(temp).map(String::trim).collect(Collectors.toList());
		// 初始化最终的表数据集合
		List<String> finalTbls = new ArrayList<>();
		Connection connection = config.getConn();
		MySqlQuery querySQL = new MySqlQuery();
		// QuerySQL querySQL = getQuerySQL(config.getDbType());
		PreparedStatement preparedStatement = null;
		try {
			preparedStatement = connection.prepareStatement(querySQL.tablesSql());
			ResultSet results = preparedStatement.executeQuery();
			while (results.next()) {
				String tableName = results.getString(querySQL.tableName());
				String comment = results.getString(querySQL.tableComment());
				if (!StringUtils.isEmpty(tableName)) {
					if (isTbl) {
						// 忽略掉mysql的视图
						if (!"VIEW".equalsIgnoreCase(comment) && isTblMatch(tableName, tbMatchList)) {
							finalTbls.add(tableName);
						}
					} else {
						if (isTblMatch(tableName, tbMatchList)) {
							finalTbls.add(tableName);
						}
					}
				} else {
					System.err.println("当前数据库为空！！！");
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			try {
				if (preparedStatement != null) {
					preparedStatement.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("符合要求的表名：" + finalTbls);
		String[] finalTblArr = new String[finalTbls.size()];
		return finalTbls.toArray(finalTblArr);
	}

}
